<template>
  <div class="seach-container">
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        background="#5babfb"
        show-action
        @search="onSearch(searchText)"
        @cancel="onCancel"
        @focus="isResultShow = false" />
    </form>
    <search-results v-if="isResultShow" :search-text="searchText"></search-results>
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
      ></search-suggestion>
    <search-history
      v-else
      :search-histories="searchHistories"
      @update-search-histories="updateSearchHistories"
      @search="onSearch"></search-history>
  </div>
</template>

<script>
import { mapState } from 'Vuex'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchHistory from './components/search-history.vue'
import SearchResults from './components/search-results.vue'
import { setItem, getItem } from '@/utils/storage.js'
// import { getSearchHistories } from '@/api/search.js'
export default {
  name: 'SearchIndex',
  props: {},
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResults
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: []
    }
  },
  computed: {
    ...mapState({
      user: state => state.user.user
    })
  },
  watch: {
    searchHistories () {
      setItem('SEARCH_HISTORIES', this.searchHistories)
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    },
    async loadSearchHistories () {
      // if (this.user) {
      //   const { data } = await getSearchHistories()
      //   this.searchHistories = data.data.keywords
      // } else {
      //   this.searchHistories = getItem('SEARCH_HISTORIES') || []
      // }
      this.searchHistories = getItem('SEARCH_HISTORIES') || []
    },
    updateSearchHistories () {
      this.searchHistories = []
    }
  },
  created () {
    this.loadSearchHistories()
  },
  mounted () {
  },
  destroyed () {
  }
}
</script>

<style scoped lang='less'>
</style>
